package responder

import (
	"errors"

	"github.com/bitwormhole/starter/application"
)

type Registration struct {
	Host        string
	Port        int
	ContextPath string

	Filters     []Filter
	Controllers []Controller
	Factory     ContainerBuilderFactory

	container Container
	context   application.Context
}

func (inst *Registration) Inject(ctx application.Context) error {
	inst.context = ctx
	return nil
}

func (inst *Registration) init() error {

	container := inst.container
	if container != nil {
		return nil
	}

	cfg := &ContainerConfig{}
	cfg.Host = inst.Host
	cfg.Port = inst.Port

	builder := inst.Factory.NewBuilder()
	builder.SetConfig(cfg)
	builder.SetFilters(inst.Filters)

	err := inst.regControllers(builder)
	if err != nil {
		return err
	}

	container = builder.Create()
	inst.container = container
	return nil
}

func (inst *Registration) regControllers(builder ContainerBuilder) error {
	list := inst.Controllers
	if list == nil {
		return nil
	}
	for index := range list {
		ctrl := list[index]
		if ctrl == nil {
			continue
		}
		err := ctrl.Config(builder)
		if err != nil {
			return err
		}
	}
	return nil
}

func (inst *Registration) Start() error {
	err := inst.init()
	if err != nil {
		return err
	}
	container := inst.container
	if container == nil {
		return errors.New("no container")
	}
	return container.Start()
}

func (inst *Registration) Stop() error {
	container := inst.container
	if container == nil {
		return errors.New("no container")
	}
	return container.Stop()
}
